/**
 * @author Chad Dettmering
 */

package org.flckphoto;

import java.io.*;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.*;

/**
 * This activity is used to set the user settings
 */
public class SettingsActivity extends Activity {
	/**
	 * Tag for log output
	 */
	private static final String TAG = "SettingsActivity";
	
	/**
	 * reference to the "save" button
	 */
	private Button saveButton;
	
	/**
	 * reference to the "cancel" button
	 */
	private Button cancelButton;
	
	/**
	 * reference to the text box, where the user
	 * inputs their username for Flickr
	 */
	private EditText userText;
	
	/**
	 * reference to the text box, where the user
	 * inputs their password for Flickr
	 */
	private EditText passText;
	
	/**
	 * overrides the onCreate for this activity to display
	 * the settings layout
	 * 
	 * @param bundle the Bundle object given by Android OS
	 */
	@Override
	public void onCreate(Bundle bundle) {
		super.onCreate(bundle);
		
		//show the settings layout
		Log.d(TAG, "Preparing layout");
		setContentView(R.layout.settings);
		saveButton = (Button) findViewById(R.id.saveButton);
		cancelButton = (Button) findViewById(R.id.cancelButton);
		userText = (EditText) findViewById(R.id.editUsername);
		passText = (EditText) findViewById(R.id.editPassword);
		
		//initiate the fields using the username and password 
		//we have already
		userText.setText(Settings.username);
		passText.setText(Settings.password);
		
		
		//setup the save button
		saveButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v){
				try {
					//open up the settings file
					Log.d(TAG, "Opening settings file and reading data");
					FileOutputStream f = openFileOutput(Settings.FILENAME,
														Context.MODE_PRIVATE);
					
					Log.d(TAG, "Saving the new username and password");
					//change the settings to reflect the new username and password
					Settings.username = userText.getText().toString();
					Settings.password = passText.getText().toString();
					String auth = "";
					
					//auth token should always be available
					auth = Settings.authToken;
					
					//concatenate the username and password
					String userPass = Settings.username + " " + Settings.password + " " + auth; 
					
					//write it to the settings file
					f.write(userPass.getBytes());
					f.close();
				} catch(FileNotFoundException e) {
					Log.e(TAG, "Settings file not found! " + e.getMessage());
				} catch(IOException e){
					Log.e(TAG, e.getMessage());
					
				}
			}
		});
		
		//setup the cancel button
		cancelButton.setOnClickListener( new OnClickListener() {
			@Override
			public void onClick(View v) {
				//just exit the activity if we cancel
				Log.d(TAG, "Cancel button clicked, exiting settings activity");
				finish();
			}
		});
	}

}
